<template>
  <BasicModal
    @register="registerModal"
    v-bind="$attrs"
    title="Import widget"
    @ok="handleSubmit"
    ok-text="保存"
  >
    <Upload accept=".json" :maxCount="1" :beforeUpload="handleBeforeUpload">
      <a-button> 选择JSON格式文件 </a-button>
    </Upload>
  </BasicModal>
</template>

<script setup lang="ts">
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { Upload } from 'ant-design-vue';
  import { ref } from 'vue';

  const emit = defineEmits(['success']);
  const jsonValue = ref<any>();
  const mode = ref('');
  const [registerModal, { closeModal }] = useModalInner((data) => {
    mode.value = data.key;
  });
  const handleBeforeUpload = (file: File) => {
    const fileReader = new FileReader();
    fileReader.readAsText(file);
    fileReader.onload = async (e) => {
      jsonValue.value = JSON.parse(e.target?.result as string);
    };
    return false;
  };
  const handleSubmit = () => {
    closeModal();
    emit('success', mode.value, { jsonValue: jsonValue.value });
  };
</script>
